package com.huixi.microspur.web.security.handler;

import com.huixi.microspur.commons.util.wrapper.WrapMapper;
import com.huixi.microspur.web.config.JWTConfig;
import com.huixi.microspur.web.pojo.entity.user.WjUser;
import com.huixi.microspur.web.util.JWTTokenUtil;
import com.huixi.microspur.web.util.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description 登录成功处理类
 * @Author Sans
 * @CreateTime 2019/10/3 9:13
 */
@Slf4j
@Component
public class UserLoginSuccessHandler implements AuthenticationSuccessHandler {

    /**
     * 登录成功返回结果
     * @Author Sans
     * @CreateTime 2019/10/3 9:27
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication){
        // 组装JWT
        WjUser wjUser =  (WjUser) authentication.getPrincipal();
        String token = JWTTokenUtil.createAccessToken(wjUser);
        token = JWTConfig.tokenPrefix + token;

        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("wjUser", wjUser);

        ResultUtil.responseJson(response, WrapMapper.ok(map));


    }


}
